import Observer from '../observer/index'

export default function initData(vm) {
    let data = vm.$options.data
    data = vm._data = typeof data === 'function'
        ? data.call(vm)
        : data || {}

    // proxy data on instance
    const keys = Object.keys(data)
    let i = keys.length

    while (i--) {
        proxy(vm, `_data`, keys[i])
    }

    new Observer(data)
}

const sharedPropertyDefinition = {
    enumerable: true,
    configurable: true,
    get: '',
    set: ''
}

export function proxy(target, sourceKey, key) {
    sharedPropertyDefinition.get = function proxyGetter() {
        return this[sourceKey][key]
    }
    sharedPropertyDefinition.set = function proxySetter(val) {
        this[sourceKey][key] = val
    }
    Object.defineProperty(target, key, sharedPropertyDefinition)
}
